﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion;
using Furion.DatabaseAccessor;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using YShop.Application.Contracts.Shop;
using YShop.Application.Contracts.System.DataItems;
using YShop.Core;
using YShop.Core.Entites.Shop;
using YShop.Core.Managers.Caches;
using Attribute = YShop.Core.Entites.Shop.Attribute;

namespace YShop.Application.Shop
{
    /// <summary>
    /// 商品属性
    /// </summary>
    [ApiDescriptionSettings("Shop")]
    [Route("api/attribute")]
    public class AttributeService : CrudMasterSlave1Service<Attribute, AttributeDetail, ProductOptionDto, ProductOptionDto, PageSearchDto, ProductOptionDto, ProductOptionDto>, IBaseService
    {
        private readonly IRepository<Core.Entites.Shop.Attribute> _repository;

        public override string EntitiesCacheKey => CacheKeys.ProductOptions;
        public override List<Core.Entites.Shop.Attribute> EntitiesCache => App.GetService<CacheManager>().GetOrCreate(CacheKeys.ProductOptions, _ => 
        {
            var results = _repository.Include(s => s.Items).ToList();
            results.ForEach(s => s.ItemJoin = string.Join(" / ", s.Items.Select(i=>i.Name)));
            return results;
        });
        public AttributeService(IRepository<Core.Entites.Shop.Attribute> repository,IRepository<AttributeDetail> itemRepository) : base(repository, itemRepository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 获取数据项
        /// </summary>
        /// <returns></returns>
        [SystemDataItem(code: "Attribute", type: DataItemDetailsDataType.List)]
        public List<DataItemDetailDto> GetItems() => EntitiesCache.Select(s => new
        DataItemDetailDto
        {
            Value = s.Id,
            Label = s.Name,
            Params = s.Items,
        }).ToList();
    }
}
